package com.superman.mvpframe.client.widget.tabbar;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.superman.mvpframe.client.widget.tabbar.MyTabBarSelectEvent.MyTabBarSelectHandler;

/**
 * tab
 * 
 * @author superman
 * @version 2018年8月7日下午1:25:00
 */
public class MyTabBar extends FlowPanel implements HasMyTabBarSelectHandler {

	/**
	 * 构造方法
	 * 
	 * @author superman
	 * @version 2018年8月7日 下午1:25:02
	 */
	public MyTabBar() {
		this.addStyleName("flex-h flex-hc bd-b-1px ddd");
		this.setSize("10rem", "1.33333rem");
		this.getElement().getStyle().setProperty("background", "#fff");
	}

	@Override
	public HandlerRegistration addMyTabBarSelectHandler(MyTabBarSelectHandler myTabBarSelectHandler) {
		return addHandler(myTabBarSelectHandler, MyTabBarSelectEvent.getType());
	}

	/**
	 * 添加tab
	 * 
	 * @author superman
	 * @version 2018年8月7日 下午1:28:31
	 * @param tabName
	 */
	public void addTab(String tabName) {
		final HTML html = new HTML(tabName);
		html.addStyleName("flex1");
		html.getElement().getStyle().setProperty("textAlign", "center");
		html.getElement().getStyle().setProperty("fontSize", "13px");
		html.getElement().getStyle().setProperty("color", "#333");
		html.getElement().getStyle().setProperty("lineHeight", "1.33333rem");
		html.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				select(MyTabBar.this.getWidgetIndex(html));
			}
		});

		this.add(html);
	}

	private void changeStyle(int index) {
		for (int i = 0; i < this.getWidgetCount(); i++) {
			Widget w = this.getWidget(i);
			if (i == index) {
				w.getElement().getStyle().setProperty("borderBottom", "1px solid #e31436");
				w.getElement().getStyle().setProperty("color", "#e31436");
			} else {
				w.getElement().getStyle().setProperty("borderBottom", "none");
				w.getElement().getStyle().setProperty("color", "#333");
			}
		}
	}

	/**
	 * 选中
	 * 
	 * @author superman
	 * @version 2018年8月8日 下午10:02:59
	 * @param index
	 */
	public void select(int index) {
		changeStyle(index);
		MyTabBarSelectEvent.fire(this, index);
	}

	/**
	 * 选中
	 * 
	 * @author superman
	 * @version 2018年8月8日 下午10:02:59
	 * @param index
	 * @param fireEvent
	 */
	public void select(int index, boolean fireEvent) {
		changeStyle(index);
		if (fireEvent)
			MyTabBarSelectEvent.fire(this, index);
	}

}
